var createError = require('http-errors');
var express = require('express');
var cors = require('cors')
var ejs = require('ejs');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require("body-parser")



var ApiRouter = require('./routes/api/index');


var app = express();
// var http = require('http');
// var server = http.createServer(app, (req, res) => {
//     var pathname = url.parse(req.url).pathname;
//     // 关闭nodejs 默认访问 favicon.ico
//     if (!pathname.indexOf('/favicon.ico')) {
//         return;
//     };
// });

// var io = require('socket.io')(server);


app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

//设置跨域访问
app.all('*', function(req, res, next) {

    // 设置请求头为允许跨域
    if (req.headers.origin == "http://127.0.0.1:8080" || req.headers.origin == "http://localhost:8080") {
        res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
        // 设置服务器支持的所有头信息字段
        res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With ');
        res.header('Content-Type', 'application/json; charset=utf-8');
        res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
        res.header("X-Powered-By", ' 3.2.1')
            //允许携带信息头
        res.header('Access-Control-Allow-Credentials', true);
    }
    req.method === 'OPTIONS' ? res.status(200).end() : next()


});

// view engine setup

app.engine('html', ejs.__express);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
// app.disable('etag');


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));



app.get("/", cors(), (req, res) => {
        res.render("index")
    })
    // io.on('connection', (socket) => {
    //     console.log("连接好了");

// });
app.use('/api', ApiRouter);




// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.send("没有这个页面");
});



module.exports = app;
// module.exports = [app, server];